package com.android.basewars;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class BaseWarsActivity extends MapActivity {
	/** Called when the activity is first created. */
	MapView mapView;
	public JSONArray results;
	int userID;
	int[] help;
	String gpsLat;
	String gpsLon;
	protected String[] ownBases;
	protected JSONArray ownBasesresult;
	protected JSONArray Baseresult;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);

		 Bundle extras = getIntent().getExtras();
		    if(extras !=null)
		    {
		    	userID = extras.getInt("userid");
		    	getAllBases();// TODO
				
				// GPS LOCATIOn
				LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				LocationListener mlocListener = new MyLocationListener();
				mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
						mlocListener);
		    }
		   gpsLat = "51.941662";
		   gpsLon = "4.382413";
		    
		    setGPSMarker(gpsLat, gpsLon);// TODO debug
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menumap, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.mapview:
//	    	Intent m = new Intent(getApplicationContext(), BaseWarsActivity.class);
//	 		m.putExtra("userid", userID);
//	 		startActivity(m);
//	 		finish();
	        return true;
	    case R.id.rankinglist:
	    	Intent rl = new Intent(getApplicationContext(), RankingActivity.class);
	 		rl.putExtra("userid", userID);
	 		startActivity(rl);
	 		finish();
	        return true;
	    case R.id.attacklog:
	    	Intent al = new Intent(getApplicationContext(), AttackLogActivity.class);
	 		al.putExtra("userid", userID);
	 		startActivity(al);
	 		finish();
	        return true;
	    case R.id.editaccount:
	    	Intent e = new Intent(getApplicationContext(), EditAccountActivity.class);
	 		e.putExtra("userid", userID);
	 		startActivity(e);
	 		finish();
	        return true;  
	    case R.id.refreshmap:
	    	getAllBases();
	        return true;  
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	
	private void getAllBases() {
		Handler handler = new Handler() {
			
			public void handleMessage(Message message) {
				switch (message.what) {
				case HttpConnection.DID_START: {
					break;
				}
				case HttpConnection.DID_SUCCEED: {
					String response = (String) message.obj;
					try {
						JSONObject bases = new JSONObject(response);
						boolean b = bases.getBoolean("success");
						if(b){
							results = bases.getJSONArray("result");
							
							setBases();
						
				 		}else{
				 			//geen basisen
						}
					}
					catch (JSONException e) {
						e.printStackTrace();
					}
					break;
				}
				case HttpConnection.DID_ERROR: {
					Exception e = (Exception) message.obj;
					e.printStackTrace();
					break;
				}
				}
			}
		};
		new HttpConnection(handler)
				.get("http://frankkie.nl/basewars/api/v4/bases2");
		
	}
	public void setBases(){
		List<Overlay> mapOverlays = mapView.getOverlays();
		
		//ENEMY BASES
		Drawable enemyBaseIcon = this.getResources().getDrawable(
				R.drawable.enemybase);
		ItemOverlay itemizedoverlay = new ItemOverlay(enemyBaseIcon, this);
		int maxID = 0;		
		for(int i = 0; i < results.length(); i++){
			try {
				JSONObject base = results.getJSONObject(i);
				//enmy basis
				if(Integer.parseInt(base.getString("id")) > maxID){
					maxID = Integer.parseInt(base.getString("id"));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		help = new int[maxID + 1];
		for(int j = 0; j < results.length(); j++){
			try {
				JSONObject base = results.getJSONObject(j);
				
				help[Integer.parseInt(base.getString("id"))] = j;
			}
				catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		ownbases = new JSONArray();
		for(int i = 0; i < /*results.length() TODO*/20; i++){
			try {
				JSONObject base = results.getJSONObject(i);
				//enmy basis
				if(Integer.parseInt(base.getString("id")) > maxID){
					maxID = Integer.parseInt(base.getString("id"));
				}
				
				if( Integer.parseInt(base.getString("player_id")) != userID ){
					String lat = base.getString("loc_latitude");
					String lon = base.getString("loc_longitude");
					
					String description = base.getString("description");
					String name = base.getString("base_name");
					
					GeoPoint point = gpslocatie(lat, lon);
					OverlayItem overlayitem = new OverlayItem(point, "EBASE",
							base.getString("id") );
					
					itemizedoverlay.addOverlay(overlayitem, results, String.valueOf(userID), help );
				}
				// mijn basis
				else if( Integer.parseInt(base.getString("player_id")) == userID){
					ownbases.put(base);
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
		mapOverlays.add(itemizedoverlay);
		//OWN BASES
		Drawable ownBaseIcon = this.getResources().getDrawable(
				R.drawable.ownbase);
		ItemOverlay itemizedoverlay2 = new ItemOverlay(ownBaseIcon, this);
		
		for(int i = 0; i < ownbases.length(); i++){
			try {
				JSONObject base = ownbases.getJSONObject(i);
					String lat2 = base.getString("loc_latitude");
					String lon2 = base.getString("loc_longitude");
					
					String description2 = base.getString("description");
					String name2 = base.getString("base_name");
					
					GeoPoint point2 = gpslocatie(lat2, lon2);
					OverlayItem overlayitem2 = new OverlayItem(point2, "OWNBASE",
							base.getString("id"));
					
					itemizedoverlay2.addOverlay(overlayitem2,results, String.valueOf(userID), help, gpsLat, gpsLon);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		if(ownbases.length() > 0){
			mapOverlays.add(itemizedoverlay2);
		}
	}
	
	JSONArray ownbases;// = new
	
	
	public GeoPoint gpslocatie(String lat1, String lot1) {
		double lat = Double.parseDouble(lat1);
		double lng = Double.parseDouble(lot1);

		GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
		return p;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			// LOGOUT!
			Intent start = new Intent(getApplicationContext(),
					LogInActivity.class);
			startActivity(start);
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	public void setGPSMarker(String lat, String lon){
		List<Overlay> mapOverlays = mapView.getOverlays();
		mapOverlays.clear();
		//setBases(); //TODO debug
		Drawable drawable = this.getResources().getDrawable(R.drawable.user);
		ItemOverlay itemizedoverlay = new ItemOverlay(drawable, this);

		
		GeoPoint point = gpslocatie(lat, lon);
		OverlayItem gpsLocatie = new OverlayItem(point, "GPS",
				String.valueOf(userID) );

		itemizedoverlay.addOverlay(gpsLocatie, gpsLat, gpsLon);
		mapOverlays.add(itemizedoverlay);
	}

	/* Class My Location Listener */
	public class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location loc) {
			double lat = loc.getLatitude();
			double lon = loc.getLongitude();
			String Text = "My current location is: " + "Latitud = "
					+ loc.getLatitude() + "Longitude = " + loc.getLongitude();
		//	Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT)
		//			.show();
			
			setGPSMarker( Double.toString(loc.getLatitude()) , Double.toString(loc.getLongitude()) );		
					
			
		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Disabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Enabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// Toast.makeText( getApplicationContext(), "statuschange",
			// Toast.LENGTH_SHORT ).show();
		}

	}
}